layui.define(['jquery', 'loading', 'notice', 'popup', 'toast'], function (exports) {
    let $ = layui.jquery;
    let loading = layui.loading;
    let notice = layui.notice;
    let popup = layui.popup;
    let toast = layui.toast;
    const tool = {
        loading: {
            Load: function (type, msg) {
                loading.Load(type, msg);
            },
            remove: function (time) {
                loading.loadRemove(time);
            },
            block: function (type, elem, msg) {
                loading.block({type: type, elem: type, msg: msg})
            },
            removeBlock: function (elem, time) {
                loading.blockRemove(elem, time);
            }
        },
        msg: {
            success: function (msg, type) {
                if (type == null || type === 1)
                    notice.success(msg)
                else if (type === 2)
                    popup.success(msg)
            },
            error: function (msg, type) {
                if (type == null || type === 1)
                    notice.error(msg)
                else if (type === 2)
                    popup.failure(msg)
            },
            warning: function (msg, type) {
                if (type == null || type === 1)
                    notice.warning(msg)
                else if (type === 2)
                    popup.warming(msg)
            },
            clear: function () {
                notice.clear();
            }
        },
        message: function (msg) {
            notice.info(msg);
        },
        toast: {
            success: function (title, msg, position) {
                toast.success({title: title, message: msg, position: position == null ? "topRight" : position})
            },
            error: function (title, msg, position) {
                toast.error({title: title, message: msg, position: position == null ? "topRight" : position})
            },
            warning: function (title, msg, position) {
                toast.warning({title: title, message: msg, position: position == null ? "topRight" : position})
            },
            info: function (title, msg, position) {
                toast.info({title: title, message: msg, position: position == null ? "topRight" : position})
            },
            clean: function () {
                toast.destroy()
            }
        },
        serializeObject: function (_$) {//将form转json对象
            var o = {};
            var a = _$.serializeArray();
            $.each(a, function (index, _this) {
                if (o[_this.name]) {
                    if (!o[_this.name].push) {
                        o[_this.name] = [o[_this.name]];
                    }
                    o[_this.name].push(_this.value || '');
                } else {
                    o[_this.name] = _this.value || '';
                }
            });
            return o;
        },
        JsonToHtmlValById: function (json, parent) {//json通过id注入到元素的value
            for (var key in json) {
                var value = json[key];
                var childId = "#" + key;
                if (parent !== undefined) {
                    if (typeof parent === "object") {
                        parent.find(childId).val(value);
                    } else
                        $("#" + parent).find(childId).val(value);
                } else
                    $(childId).val(value);
            }
        },
        JsonToHtmlValByName: function (json, parent) {//json通过name注入到元素的value
            for (var key in json) {
                var value = json[key];
                var childId = "[name=" + key + "]";
                if (parent !== undefined) {
                    let it;
                    if (typeof parent === "object") {
                        it = parent.find(childId);
                    } else
                        it = $("#" + parent).find(childId)
                    if (it.attr('type') !== 'radio')
                        it.val(value);
                } else
                    $(childId).val(value);
            }
        },
        JsonToHtmlTextById: function (json, parent) {//json通过id注入到元素的text
            for (var key in json) {
                var value = json[key];
                var childId = "#" + key;
                if (parent !== undefined) {
                    if (typeof parent === "object") {
                        parent.find(childId).text(value);
                    } else
                        $("#" + parent).find(childId).text(value);
                } else
                    $(childId).text(value);
            }
        },
        getLayuiTableHeight: function (other) {//获取窗口高度，名称起错了，凑乎用吧
            return other == null ? $(window).height() : $(window).height() - other;
        },
        preview: function (src, size = undefined) {//图片查看工具
            var img = new Image();
            img.src = src;
            var loadIndex = parent.layer.load(0);
            img.onerror = () => {
                parent.layer.close(loadIndex);
                parent.layer.msg("图片加载失败");
            };
            img.onload = () => {
                parent.layer.close(loadIndex);
                var height, width;
                var imgHtml = "<img src='" + src + "' ";
                if (size === undefined) {//显示图片原始大小
                    //获取当前窗口大小
                    var winHeight = $(tool.getParent().window).height() - 100;
                    var winWidth = $(tool.getParent().window).width() - 50;
                    if (img.height >= winHeight)//获取图片高度
                        height = winHeight;
                    else
                        height = img.height;
                    if (img.width >= winWidth)//获取图片宽度
                        width = winWidth;
                    else
                        width = img.width;
                    imgHtml += " />";
                } else {//自定义展示图片大小
                    height = size.height;
                    width = size.width;
                    imgHtml += " width='" + width + "px' height='" + height + "px' />";
                }
                //弹出层
                tool.getParent().layer.open({
                    type: 1,
                    shade: 0.8,
                    offset: 'auto',
                    area: [width + 'px', height + 50 + 'px'],
                    shadeClose: true,
                    scrollbar: false,
                    title: "图片预览", //不显示标题
                    content: imgHtml, //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                    cancel: function () {
                        //layer.msg('捕获就是从页面已经存在的元素上，包裹layer的结构', { time: 5000, icon: 6 });
                    }
                });
            }
        },
        getParent: function () {//获取最顶的parent
            var par = parent;
            $.each(parent, function () {
                par = par.parent;
            });
            return par;
        },
        imgsUpload: function (json, _addBack, _delBack) {//图片上传工具
            var div = json.div;
            var sum = json.sum;
            var fileList = json.fileList;
            var renew = json.renew;
            var imgSize = json.size != null ? json.size : 1024 * 1024 * 2;
            let size = div[0].clientHeight;
            let count = 0;
            if (fileList != null && Object.keys(fileList).length > 0) {
                for (var key in fileList) {
                    addImg(fileList[key], key);
                }
            } else if (sum > count) {
                addInit();
            }

            function addInit(_Renew, _RenewChange) {
                div.append('<div class="add">' +
                    '<input type="file" name="file" style="display:none; " />' +
                    '<i class="layui-icon layui-icon-add-circle-fine" style="font-size: ' + size + 'px;color: rgba(0,0,0,0.35);"></i>' +
                    '</div>');
                let _this = div.find(".add");
                let file = div.find("[name='file']");
                //选择完文件触发
                file[0].onchange = function () {
                    var fileData = this.files[0];
                    if (fileData != null)
                        if (!/image\/\w+/.test(fileData.type)) {
                            tool.msg.error("请选择正确的图片！");
                        } else if (fileData.size > imgSize) {
                            tool.msg.error("该图片文件过大！");
                        } else {
                            //初始化一个文件读取对象
                            var reader = new FileReader();
                            //读取文件数据
                            reader.readAsDataURL(fileData);
                            //读取完毕,相当于加载的过程
                            reader.onload = function (oFREvent) {
                                _this.remove();
                                //this.result就是使用base64表示的图片信息
                                let base64 = oFREvent.target.result;
                                let name = addImg(base64, fileData);
                                if (typeof _addBack === 'function')
                                    _addBack(fileData, name);
                            }
                            if (typeof _RenewChange === 'function')
                                _RenewChange(_this, file);
                        }
                }
                div.find(".add i").click(function () {
                    file.click();
                })
                if (typeof _Renew === 'function')
                    _Renew(_this, file);
            }

            function addImg(src, fileData) {
                var name = "img_" + new Date().getTime();
                div.append('<img name="' + name + '" width="115px" height="115px" src="' + src + '">');
                count++;
                div.find("[name='" + name + "']").click(function () {
                    if (renew)
                        layer.confirm('你要对这个图片做什么？', {
                            btn: ['查看', '重新上传'] //按钮
                        }, function () {
                            tool.preview(src);
                        }, function () {
                            addInit(function (_this, file) {
                                file.click();
                                _this.remove();
                            }, function () {
                                delImg(name, fileData);
                            });
                        });
                    else
                        layer.confirm('你要对这个图片做什么？', {
                            btn: ['查看', '删除'] //按钮
                        }, function () {
                            tool.preview(src);
                        }, function () {
                            delImg(name, fileData);
                            if (sum > count)
                                addInit();
                        });
                })
                if (sum > count)
                    addInit();
                return name;
            }

            function delImg(name, fileData) {
                count--;
                div.find("[name='" + name + "']").remove();
                if (typeof _delBack === 'function')
                    _delBack(fileData, name);
            }
        },
        tableAutoHeight: function (table, length, height, size) {
            if (size == null)
                size = 10
            if (length > size && table.config.height == null) {
                table.config.height = height;
                table.reload({
                    height: height
                });
            }
            if (length <= size && table.config.height != null) {
                table.config.height = null;
                table.reload({
                    height: null
                });
            }
        },
        divAppendImgs: function (srcs, div) {
            $.each(srcs, function (i, src) {
                var name = "img_" + new Date().getTime();
                div.append('<img name="' + name + '" width="50px" height="50px" src="' + src + '">');
                div.find("[name='" + name + "']").click(function () {
                    tool.preview(src);
                })
            });
        },
        hexToRgba: function (hex, opacity) {
            let rgbaColor = "";
            let reg = /^#[\da-f]{6}$/i;
            if (reg.test(hex)) {
                rgbaColor =
                    `rgba(${parseInt("0x" + hex.slice(1, 3))},${parseInt(
                        "0x" + hex.slice(3, 5)
                    )},${parseInt("0x" + hex.slice(5, 7))},${opacity})`;
            }
            return rgbaColor;
        },
        isBlank: function (value) {
            if (value != null) {
                value = $.trim(value);
                if (value !== '') {
                    return false;
                }
            }
            return true;
        },
        isNotBlank: function (value) {
            return !this.isBlank(value);
        },
        isPhoneNum: function (phone) {
            var myreg = /^1[3|4|5|7|8][0-9]{9}$/;
            return myreg.test(phone);
        },
        getRequestVal: function (variable) {    //获取url传参
            const query = window.location.search.substring(1);
            const vars = query.split("&");
            for (let i = 0; i < vars.length; i++) {
                const pair = vars[i].split("=");
                if (pair[0] === variable) {
                    return pair[1];
                }
            }
            return false;
        },
        uuid:function () {
            const s = [];
            const hexDigits = "0123456789abcdef";
            for (let i = 0; i < 36; i++) {
                s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
            }
            s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
            s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
            s[8] = s[13] = s[18] = s[23] = "-";
            return s.join("");
        }
    };

    exports('tool', tool)
});
